package com.example.dict.utils.util;


/**
 * 双向链表 用以储存单词
 * 保证单词按字典顺序有序
 * @author wey
 * */
public class LinkedList {


    /**
     * 链表大小
     * */
    private int size = 0;

    private Node first, last;

    public LinkedList() {
        first = last = new Node(null, null, null);
    }
    /**
     * @return 链表当前大小
     * */
    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }


    /**
     * 添加单词
     *
     * @param  item 记录类
     * */
    public void add(Record item) {

        if(item == null || item.translation == null) {
            return;
        }

        Node current = first.next;
        while(null != current) {
            Record r = current.item;

            if(r.word.compareTo(item.word) > 0) {
                Node node = new Node(item, current.pre, current);
                current.pre.next = node;
                current.pre = node;
                size++;
                return;
            }
            current = current.next;
        }
        Node node = new Node(item, last, null);
        last.next = node;
        last = node;
        size++;
    }



    /**
     * 获取单词
     *
     * @param word 单词
     * @return 单词及其对应的记录
     */
    public Record get(String word) {
        if (null == word || word.isEmpty()) {
            return null;
        }
        Node current = first.next;
        while(null != current) {
            Record r = current.item;
            if(r.word.equals(word)) {
                return r;
            }
            current = current.next;
        }
        return null;
    }

    /**
     * 删除单词
     * @param word 单词
     */
    public void delete(String word) {

        if (null == word) {
            return;
        }

        Node f = first.next;
        while (null != f) {

            Record item = f.item;

            if (item.word.equals(word)) {
                f.pre.next = f.next;
                f.next.pre = f.pre;
                return;
            }

            f = f.next;
        }
    }

    /**
     * 内部节点类
     * */
    private static class Node {
        Record item;
        Node pre, next;
        public Node(Record item, Node pre, Node next) {
            this.item = item;
            this.pre = pre;
            this.next = next;
        }
    }
}
